<template>
    <div class="grow">
        <div>
            <div class="staff scrolll">
                <div class="module-box1">
                    <el-select
                        v-if="props.index == 0"
                        v-model="ygId"
                        popper-class="zw-hide_select_option"
                        :popper-append-to-body="false"
                        class="selectAvataryg"
                        placeholder="请选择员工"
                        @click="ygOpenDepart">
                    </el-select>
                    <el-select
                        v-else
                        v-model="selectRow.name"
                        popper-class="zw-hide_select_option"
                        :popper-append-to-body="false"
                        class="selectAvatar"
                        placeholder="请选择客户"
                        @click="openDepart">
                    </el-select>
                    <!-- 单聊群聊 -->
                    <div class="top">
                        <div :class="['top_btn', materialId == 1 ? 'active' : '']" @click="filterMaterial(1)">单聊</div>
                        <div :class="['top_btn', materialId == 2 ? 'active' : '']" @click="filterMaterial(2)">群聊</div>
                    </div>
                    <el-input
                        v-model="department"
                        class="department"
                        maxlength="15"
                        placeholder="请输入名称进行查找"
                        @change="onChangeDepartment()"></el-input>
                </div>
                <el-scrollbar v-if="props.index == 0" class="chat">
                    <div v-if="employeeList.length" class="chat-content">
                        <div
                            v-for="item in employeeList"
                            :key="item.id"
                            class="onbu"
                            :class="selectId == item.id ? 'hover-detail-color' : ''"
                            @click="chatDetail(item)">
                            <el-image :src="item.avatar">
                                <template #error>
                                    <el-image src="/static/file/pic.png"></el-image>
                                </template>
                            </el-image>
                            <div class="cell-box">
                                <div class="cell-cont1">
                                    <span
                                        class="name spot"
                                        :title="item.name + (item.is_departure ? '(已离职)' : '')"
                                        >{{ item.name + (item.is_departure ? '(已离职)' : '') }}</span
                                    >
                                    <span class="time">{{ item.msgtime }}</span>
                                </div>
                                <div class="cell-cont2 spot">{{ item.text }}</div>
                            </div>
                        </div>
                        <div v-if="employeeList.length < total" class="load-more" @click="getMoreStaffChatList">
                            点击加载更多..
                        </div>
                        <div v-else class="load-more">没有更多了</div>
                    </div>
                    <div v-else class="chat-default">暂无数据</div>
                    <!-- <div class="chat" v-if="props.index == 0">
          </div> -->
                </el-scrollbar>
                <el-scrollbar v-else class="chat">
                    <div v-if="customerList.length" class="chat-content">
                        <div
                            v-for="item in customerList"
                            :key="item.id"
                            class="onbu"
                            :class="selectId == item.id ? 'hover-detail-color' : ''"
                            @click="chatDetail(item)">
                            <el-image
                                :src="item.avatar"
                                style="width: 36px; height: 36px; vertical-align: middle; margin-right: 5px">
                                <template #error>
                                    <el-image src="/static/file/pic.png"></el-image>
                                </template>
                            </el-image>
                            <div class="cell-box">
                                <div class="cell-cont1">
                                    <span
                                        class="name spot"
                                        :title="item.name + (item.is_departure ? '(已解散)' : '')"
                                        >{{ item.name + (item.is_departure ? '(已解散)' : '') }}</span
                                    >
                                    <span class="time">{{ item.created_at }}</span>
                                </div>
                                <div class="cell-cont2 spot">{{ item.text }}</div>
                            </div>
                        </div>
                        <div v-if="customerList.length < total" class="load-more" @click="getMoreCustomerChatList">
                            点击加载更多..
                        </div>
                        <div v-else class="load-more">没有更多了</div>
                    </div>
                    <div v-else class="chat-default">暂无数据</div>
                    <!-- <div class="chat" v-else>
          </div> -->
                </el-scrollbar>
            </div>
        </div>
        <div style="width: 100%">
            <!-- 聊天记录模块 -->
            <ChartRecord
                ref="chatRecord"
                :lt-type="materialId"
                :bembers-data="bembersData"
                :single-data="singleData"
                :msgid="msgid"
                :roomid="roomid"
                :group-data="groupData"
                :staff_id="staff_id"
                :cust_id="cust_id"
                :index="index"
                @updatagroupMember="updatagroupMember"
                @updataSingledata="updataSingledata"></ChartRecord>
            <!-- end聊天记录模块 -->

            <!-- 员工弹窗 -->
            <ZWDepart ref="DepartRef" @submit="getDepart" />

            <!-- 客户弹窗 -->
            <CustomerPopup
                ref="customerRef"
                :single-data="singleData"
                :customer="customer"
                @updateSelectRow="updateSelectRow"
                @updateContactList="updateContactList"></CustomerPopup>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { store } from '@/store';
import ChartRecord from './ChatRecord.vue';
import CustomerPopup from './CustomerPopup.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import {
    getChatList,
    getContactList,
    getContact,
    getGroupMembers,
    getCustomerLatestChat,
    getStaffLatestChat
} from '@/api/employe/riskmonitoring/messagearchiving';
import TotleData from '@/view/ecommerce/storeManage/list/components/totleData.vue';

const props = defineProps(['index']);
let suffix: any;
let input__inner: any;
const img = document.createElement('img');
let imgUrl = '';
const customer: any = ref([]);
const bembersData: any = ref([]);
const selectRow: any = ref({});
const customerList: any = ref([]);
const employeeList: any = ref([]);
const singleData = ref([]);
const groupData = ref([]);
const ygId = ref();
const value = ref();
const department = ref();
const materialId = ref<number>(1); // 聊天选择
const selectId = ref(0);
const customerRef = ref(null); // 客户弹框
const chatRecord = ref(null);
//打开新建选择人
const DepartRef = ref<any>(null);
const staffInfo = ref<any>({});
const creators: any = ref([]);
const page_size = 50;
const total = ref<number>(0);
const state = reactive<any>({
    page: 1,
    page_size: 10
});

const clientHeight = document.documentElement.clientHeight;
const height = `${clientHeight - 228}px`;
const scrollHeight = `${clientHeight - 386}px`;

onMounted(async () => {
    if (props.index === 1) {
        suffix = document.querySelector('.selectAvatar .el-input__wrapper');
        input__inner = document.querySelector('.selectAvatar .el-input__inner');
        img.className = 'avatar';
        img.style.display = 'none';
        suffix.insertBefore(img, input__inner);
        await getCustomerLatestChatFn();
    } else {
        suffix = document.querySelector('.selectAvataryg .el-input__wrapper');
        input__inner = document.querySelector('.selectAvataryg .el-input__inner');
        img.className = 'avatar';
        img.style.display = 'none';
        suffix.insertBefore(img, input__inner);
        await getStaffLatestChatFn();
    }
});

const getCustomerLatestChatFn = async () => {
    const res = await getCustomerLatestChat({ page_size });
    if (res) {
        const { data, chat_type, cust_info } = res;
        if (data && data?.length) {
            materialId.value = chat_type;
            await updateSelectRow(cust_info);
        }
    }
};
const getStaffLatestChatFn = async () => {
    const res = await getStaffLatestChat({ page_size });
    if (res) {
        const { data, chat_type, staff_info } = res;
        staffInfo.value = staff_info;
        if (data && data?.length) {
            materialId.value = chat_type;
            await getDepart([staff_info]);
        }
    }
};

const getMoreCustomerChatList = async () => {
    if (customerList.value.length < total.value) {
        state.page++;
        await getCustomerChatList();
    }
};
const getMoreStaffChatList = async () => {
    if (employeeList.value.length < total.value) {
        state.page++;
        await getStaffChatList();
    }
};

// 获取客户列表参数
let customerData = reactive({
    mobile: '',
    name: '',
    work_user_ids: [],
    page: 1, //分页页码
    page_size: 15 //每页显示数
});

// 客户列表
const fnGetContactList = () => {
    getContactList(customerData)
        .then((res: any) => {
            store.dispatch('pageTotal', res.total);
            customer.value = res.data;
        })
        .catch((err: any) => {
            // console.log(err);
        });
};
// 下一页重新获取数据
const updateContactList = (v: any) => {
    customerData = v;
    fnGetContactList();
};
const cust_id = ref('');
const updateSelectRow = async (v: any) => {
    customerList.value.splice(0);
    selectRow.value = v;
    singleData.value = [];
    cust_id.value = v.id;
    imgUrl = selectRow.value.avatar;
    suffix.style.position = 'relative';
    input__inner.style.paddingLeft = '30px';
    img.src = selectRow.value.avatar;
    img.style.display = 'block';
    await getCustomerChatList();
};

const getCustomerChatList = async () => {
    const params = {
        cust_id: cust_id.value, //外部联系人userID
        chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
        keywords: '', //聊天对象名称(员工名称/群聊名称/客户名称)
        page: state.page, //分页页码
        page_size: state.page_size //每页显示数
    };
    const { total: total_ = 0, data: data = [] } = await getContact(params);
    total.value = total_;
    if (data?.length) {
        customerList.value.push(...data);
        chatDetail(customerList.value[0]);
    }
};

const onChangeDepartment = () => {
    state.page = 1;
    // 客户
    const customerChat = reactive({
        cust_id: selectRow.value.id, //外部联系人userID
        chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
        keywords: department.value, //聊天对象名称(员工名称/群聊名称/客户名称)
        page: state.page, //分页页码
        page_size: state.page_size //每页显示数
    });
    //  员?
    const staffChat = reactive({
        staff_id: creators.value[0]?.id, //外部联系人userID
        chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
        keywords: department.value, //聊天对象名称(员工名称/群聊名称/客户名称)
        page: state.page, //分页页码
        page_size: state.page_size //每页显示数
    });

    if (selectRow.value.id || creators.value[0]?.id) {
        if (props.index == 0) {
            getChatList(staffChat).then(({ data, total: total_ = 0 }: any) => {
                total.value = total_;
                employeeList.value.splice(0);
                if (data?.length) {
                    employeeList.value.push(...data);
                }
            });
        } else {
            getContact(customerChat).then(({ data, total: total_ = 0 }: any) => {
                total.value = total_;
                customerList.value.splice(0);
                if (data?.length) {
                    customerList.value.push(...data);
                }
            });
        }
    }
};

watch(
    () => props.index,
    val => {
        if (val === 1) {
            fnGetContactList();
        }
    },
    {
        immediate: true
    }
);

// 员工弹窗
const ygOpenDepart = () => {
    DepartRef.value.departVisble = true;
    DepartRef.value.multiple = false;
    if (staffInfo.value && staffInfo.value.id) {
        DepartRef.value.selectedMember = [staffInfo.value];
    }
};

// 获取部门成员
const staff_id = ref('');
const getDepart = async (res: any) => {
    employeeList.value.splice(0);
    msgid.value = '';
    roomid.value = '';
    staffInfo.value = res.length ? res[0] : {};
    ygId.value = '';
    imgUrl = '';
    creators.value = res;
    staff_id.value = res[0]?.id;
    DepartRef.value.departVisble = false;
    creators.value.forEach(item => {
        imgUrl = item.avatar;
        ygId.value = item.name;
    });
    suffix.style.position = 'relative';
    input__inner.style.paddingLeft = '30px';
    img.src = imgUrl;
    img.style.display = 'block';
    await getStaffChatList();
};

const getStaffChatList = async () => {
    const params = {
        staff_id: staff_id.value, //员工ID
        chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
        keywords: '', //聊天对象名称(员工名称/群聊名称/客户名称)
        page: state.page, //分页页码
        page_size: state.page_size //每页显示数
    };
    const { total: total_ = 0, data: data = [] } = await getChatList(params);
    total.value = total_;
    if (data?.length) {
        employeeList.value.push(...data);
        chatDetail(employeeList.value[0]);
    }
};

// 聊天筛选
const filterMaterial = (v: any) => {
    msgid.value = '';
    roomid.value = '';
    materialId.value = v;
    value.value = '';
    department.value = '';
    chatRecord.value.start = true;
    state.page = 1;
    // 清空查询条件
    chatRecord.value.resetParams();
    // 员工检索列表
    if (props.index == 0) {
        const params = {
            staff_id: staff_id.value, //员工ID
            chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
            keywords: '', //聊天对象名称(员工名称/群聊名称/客户名称)
            page: state.page, //分页页码
            page_size: state.page_size //每页显示数
        };

        if (params.staff_id !== '') {
            getChatList(params).then(({ data, total: total_ = 0 }: any) => {
                total.value = total_;
                employeeList.value.splice(0);
                if (data?.length) {
                    employeeList.value.push(...data);
                    chatDetail(employeeList.value[0]);
                }
            });
        }
    } else {
        const customerChat = reactive({
            cust_id: cust_id.value, //外部联系人userID
            chat_type: materialId.value, //聊天类型  1-单聊  2-群聊
            keywords: department.value, //聊天对象名称(员工名称/群聊名称/客户名称)
            page: state.page, //分页页码
            page_size: state.page_size //每页显示数
        });
        if (customerChat.cust_id !== '') {
            getContact(customerChat).then(({ data, total: total_ = 0 }: any) => {
                total.value = total_;
                customerList.value.splice(0);
                if (data?.length) {
                    customerList.value.push(...data);
                    chatDetail(customerList.value[0]);
                }
            });
        }
    }
    // start.value = true
    // paged.value = 1
    // pageg.value = 1
};
// 客户弹窗
const openDepart = () => {
    customerRef.value.appDialog.visible = true;
    customerRef.value.radio1 = selectRow.value.id;
};

const msgid = ref('');
const roomid = ref('');
// 单聊聊天详情 后续需要优化代码
const chatDetail = (item: any) => {
    // 清空查询条件,msgid变动会触发清空，只需要处理id相同时候清空
    if (msgid.value == item.msgid) {
        chatRecord.value.resetParams();
    }
    // 员工
    if (props.index == 0) {
        if (materialId.value === 1) {
            const singleParams = {
                msgid: item.msgid,
                staff_id: staff_id.value,
                msgtype: '',
                keywords: '',
                msgtime: [],
                page: 1,
                page_size: 10
            };
            msgid.value = item.msgid;
            chatRecord.value.start = true;
        } else {
            chatRecord.value.start = true;
            roomid.value = item.roomid;
            const groupParams = {
                roomid: item.roomid,
                staff_id: staff_id.value,
                msgtype: '',
                keywords: '',
                msgtime: [],
                page: 1,
                page_size: ''
            };
            const groupMemberParams = {
                roomid: item.roomid,
                keywords: '',
                page: 1,
                page_size: 10
            };
            getGroupMembers(groupMemberParams).then((data: any) => {
                groupData.value = data;
            });
        }
    } else {
        if (materialId.value === 1) {
            msgid.value = item.msgid;
            const singleParams = {
                msgid: item.msgid,
                cust_id: cust_id.value,
                msgtype: '',
                keywords: '',
                msgtime: [],
                page: 1,
                page_size: 10
            };
        } else {
            roomid.value = item.roomid;
            const groupParams = {
                roomid: item.roomid,
                cust_id: cust_id.value,
                msgtype: '',
                keywords: '',
                msgtime: [],
                page: 1,
                page_size: ''
            };
            const groupMemberParams = {
                roomid: item.roomid,
                keywords: '',
                page: 1,
                page_size: 10
            };
            getGroupMembers(groupMemberParams).then((data: any) => {
                groupData.value = data;
            });
        }
    }

    selectId.value = item.id;
    singleData.value = [];
    chatRecord.value.paged = 1;
    chatRecord.value.pageg = 1;
};
// 单聊员工聊天详情
const updataSingledata = (v: any) => {
    singleData.value = v;
};
const updatagroupMember = (v: any) => {
    groupData.value = v;
};
// let start = ref(true)
// const paged = ref(1)
// const pageg = ref(1)
// const scroll = async () => {
//   const el = document.querySelector('.scrolll')
//   const clientHeight = el?.clientHeight
//   const scrollHeight = el?.scrollHeight
//   const scrollTop = Math.ceil(el?.scrollTop)
//   console.dir(el)
//   if (scrollTop >= scrollHeight - clientHeight) {
//     if (!start.value) return
//     if (props.index == 0) {
//       let params = {
//         staff_id: staff_id.value,
//         chat_type: materialId.value == 0 ? 1 : 2, //聊天类型  1-单聊  2-群聊
//         keywords: '', //聊天对象名称(员工名称/群聊名称/客户名称)
//         page: ++paged.value, //分页页码
//         page_size: 10 //每页显示数
//       }
//       const { data } = await getChatList(params)
//       if (data.length === 0) {
//         start.value = false
//         return
//       }
//       employeeList.value.push(...data)
//     } else {
//       let paramss = {
//         cust_id: cust_id.value,
//         chat_type: materialId.value == 0 ? 1 : 2, //聊天类型  1-单聊  2-群聊
//         keywords: department.value, //聊天对象名称(员工名称/群聊名称/客户名称)
//         page: ++pageg.value, //分页页码
//         page_size: 10 //每页显示数
//       }
//       const { data } = await getContact(paramss)
//       if (data.length === 0) {
//         start.value = false
//         return
//       }
//       customerList.value.push(...data)
//     }
//     start.value = true
//   }
// }
defineExpose({
    msgid
});
</script>

<style lang="scss" scoped>
.selectAvataryg {
    width: 217px;
}

.selectAvatar {
    width: 217px;
}

.el-input--suffix .el-input__inner {
    // width: 217px;
    padding-left: 10px;
}

:deep .el-input__icon {
    width: 12px;
}

:deep .el-select__popper.el-popper[role='tooltip'] {
    display: none;
}

:deep .avatar {
    width: 22px;
    height: 22px;
    position: absolute;
    top: 5px;
    left: 7px;
}

.grow {
    display: flex;
}

.staff {
    width: 270px;

    // min-width: 270px;
    // min-height: 800px;
    border: 1px solid #eaeaea;
    padding: 16px 0;
    position: relative;
    margin-right: 16px;
    box-sizing: border-box;

    .module-box1 {
        padding: 0 16px;

        .el-select {
            width: 100%;
        }

        .top {
            display: flex;
            width: 100%;

            &_btn {
                flex: 1;
                padding: 5px 0;
                background: #fff;
                border: 1px solid #ff6b00;
                font-size: 12px;
                color: #ff6b00;
                line-height: 16px;
                cursor: pointer;
                margin-top: 10px;
                text-align: center;
            }

            .active {
                background: #ff6b00;
                color: #ffff;
            }
        }

        .department {
            margin-top: 10px;
        }
    }

    .chat {
        margin-top: 16px;
        height: v-bind(scrollHeight);

        .chat-content {
            width: 100%;

            .onbu {
                display: flex;
                padding: 16px 16px 0;
                cursor: pointer;
                margin-bottom: 1px;

                :deep(.el-image) {
                    flex: 0 0 36px;
                    width: 36px;
                    height: 36px;
                    vertical-align: middle;

                    .el-image__inner {
                        border-radius: 4px;
                    }
                }

                .cell-box {
                    width: 100%;
                    margin-left: 10px;
                    padding-bottom: 16px;

                    .cell-cont1 {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .name {
                            width: 60px; /* 不允许出现半汉字截断 */
                            font-size: 14px;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            color: #33302d;
                        }

                        .time {
                            font-size: 12px;
                            color: #969696;
                            white-space: nowrap;
                        }
                    }

                    .cell-cont2 {
                        width: 180px; /* 不允许出现半汉字截断 */
                        margin-top: 10px;
                        font-size: 12px;
                        color: #969696;
                    }
                }
            }

            .load-more {
                font-size: 12px;
                color: #888;
                letter-spacing: 1px;
                line-height: 24px;
                text-align: center;
                cursor: pointer;
            }
        }

        .chat-default {
            font-size: 12px;
            color: #999;
            letter-spacing: 2px;
            line-height: 200px;
            text-align: center;
        }

        // .spot {
        //   overflow: hidden; /*自动隐藏文字*/
        //   text-overflow: ellipsis; /*文字隐藏后添加省略号*/
        //   white-space: nowrap; /*强制不换行*/
        // }
    }

    .hover-detail-color {
        background-color: #fffaf9;
    }
}

.scrolll {
    height: v-bind(height);

    // overflow: scroll;
    // overflow-x: hidden;
    // &::-webkit-scrollbar {
    //   display: none;
    // }
}
</style>
